﻿using System;
using System.Windows;
using Mesuro.DataManagement;

namespace Mesuro.GUI {
	/// <summary>
	/// Interaction logic for OptionsDialog.xaml
	/// </summary>
	public partial class OptionsDialog : Window {
		Database _database = new Database();

		public Database Database {
			get { return _database; }
			set { _database = value; }
		}

		public OptionsDialog() {
			this.InitializeComponent();

			// Insert code required on object creation below this point.
		}

		private void btnTest_Click( object sender, RoutedEventArgs e ) {
			lblConnectionState.Text = "Connecting...";
			//Schedule and delay a connection to database to ensure there is enough time for 
			//the user to see that the connection attempt has started.
			Dispatcher.BeginInvoke( (Action)delegate() {
				System.Threading.Thread.Sleep( 500 );
				Database.DataSource = txtServer.Text;
				int port;
				if (!Int32.TryParse( txtPort.Text, out port ))
					port = 3306;
				Database.Port = port;
				Database.Username = txtUser.Text;
				Database.Password = pwdPassword.Password;
				Database.DatabaseName = txtDatabase.Text;
				Database.Encrypt = chkSSL.IsChecked ?? true;
				Database.PersistSecurity = chkPersist.IsChecked ?? false;
				if (!Database.Connect()) {
					MessageBox.Show( Database.LastError.Message, "MySQL Connnection Failed", MessageBoxButton.OK, MessageBoxImage.Error );
					Dispatcher.BeginInvoke( (Action)(() => lblConnectionState.Text = Database.LastError.Message) );
				} else
					Dispatcher.BeginInvoke( (Action)(() => lblConnectionState.Text = "Connected to database successfully!") );

				Database.Disconnect();
			}, System.Windows.Threading.DispatcherPriority.Background );
		}

		private void btnBackup_Click( object sender, RoutedEventArgs e ) {
			//5Database.CreateFullBackup( dlgSave );
		}
	}
}